#include "xdemux_task.h"
extern "C" {
#include <libavformat/avformat.h>
}
#include <chrono>
using namespace std;

bool XDemuxTask::Open(const std::string &url, int timeout_ms) {
  LOGDEBUG("XDemuxTask::Open begin");
  demux_.set_c(nullptr); // 清楚原来的
  this->url_ = url;
  this->timeout_ms_ = timeout_ms;
  AVFormatContext *c = demux_.Open(url.c_str());
  if (!c)
    return false;
  demux_.set_c(c);
  demux_.set_time_out_ms(timeout_ms);
  LOGDEBUG("XDemuxTask::Open end");
  return true;
}

void XDemuxTask::Main() {
  AVPacket pkt;
  while (!is_exit()) {
    if (!demux_.Read(&pkt)) {
      // 读取失败
      cout << "-" << flush;
      if (!demux_.is_connected() || demux_.IsTimeout()) {
        XDemuxTask::Open(url_, timeout_ms_);
      }
      std::this_thread::sleep_for(10ms);
      continue;
    }
    cout << "." << flush;
    // 传递给下一个线程
    Next(&pkt);
    av_packet_unref(&pkt);
    std::this_thread::sleep_for(10ms);
  }
  demux_.set_c(nullptr);
}
